package com.buba.utils;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Excel工具类
 */
public class ExcelUtils<T> {
    private Workbook workbook;
    private Sheet sheet;
//    private Row row;
//    private Cell cell;
    /**
     * 导出方法
     * @Param list要导出的数据
     * OutputStream outputStream
     *  @Param response输出给浏览器的对象
     * @Param c要导出的数据对应 实体类
     * @Param name excel名字
     */
    public  void export(List<T> list, HttpServletResponse response,Class c,String name) throws IOException, IllegalAccessException {
        //创建工作簿
        workbook = new XSSFWorkbook();
        //创建页
        sheet = workbook.createSheet();
        //表头行
       Row headRow = sheet.createRow(0);
       //获取类中所有属性
        Field[] declaredFields = c.getDeclaredFields();
        //定义一个集合用于装入有@MyCell标记的属性
        List<Field> fieldList = new ArrayList<>();
       for(Field field:declaredFields){
           MyCell annotation = field.getAnnotation(MyCell.class);
           if (annotation != null){
               fieldList.add(field);
           }

       }
       //定义表头
        int index = 0 ;
        for (Field f:fieldList) {
            String value = f.getAnnotation(MyCell.class).value();
            headRow.createCell(index++).setCellValue(value);
        }
        
        //向excel中输入内容  
        //空出表头的行，所以从下标为1开始创建
        int count = 1;
        for (T t : list) {
            Row row = sheet.createRow(count++);
            //遍历有注解的属性
            int cellCount = 0;
            for (Field f : fieldList) {
                f.setAccessible(true);
                Cell cell = row.createCell(cellCount++);
                cell.setCellValue(f.get(t).toString());
            }
        }



        //将excel返回给浏览器下载
        OutputStream outputStream = response.getOutputStream();
        response.reset();
        response.setHeader("Content-disponsition","attachment; filename=" + name + ".xlsx");
        response.setContentType("application/msexcel");
        workbook.write(outputStream);
        outputStream.close();
    }
}
